package com.example.blogback.jwt;

import cn.hutool.json.JSONUtil;
import com.example.blogback.common.Result;
import com.example.blogback.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class JwtFilter extends AuthenticatingFilter {
    @Autowired
    JwtUtils jwtUtils;
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        log.info("执行JwtFilter的createToken方法-------->");
        HttpServletRequest request=(HttpServletRequest) servletRequest;

//        获取头信息
        String jwt = request.getHeader("Authorization");
        if(Strings.isEmpty(jwt)){
            return null;
        }
        return new JwtToken(jwt);
    }


    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        log.info("执行JwtFilter的onAccessDenied方法-------->");
        HttpServletRequest request=(HttpServletRequest) servletRequest;

//        获取头部的Authorization
        String jwt = request.getHeader("Authorization");
        System.out.println("jwt==="+jwt);
        if(Strings.isEmpty(jwt)){
            System.out.println("JWT为空");
//            为true，此时拒绝登录，应该让过滤器继续处理
            return true;
        } else {
//            对jwt进行校验
            Claims claim = jwtUtils.getClaimByToken(jwt);
            System.out.println("claim==="+claim);
            if(claim==null || jwtUtils.isTokenExpired(claim.getExpiration())){
                throw new ExpiredCredentialsException("token已失效，请重新登录");
            }
//            执行登录
            log.info("执行executeLogin方法-------->");
            return executeLogin(servletRequest,servletResponse);
        }
    }
    @Override
    public boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
                                  ServletRequest request,ServletResponse response){
        log.info("执行JwtFilter的onLoginFailure方法-------->");
        HttpServletResponse httpResponse=(HttpServletResponse) response;
        try {
            Throwable throwable=e.getCause()==null?e:e.getCause();
            Result r=Result.fail(throwable.getMessage());
            String json = JSONUtil.toJsonStr(r);
            httpResponse.getWriter().print(json);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 在Filter之前调用，提供跨域支持
     * 如果为true，会继续执行过滤链
     * isAccessAllowed为false会执行此方法
     */
    @Override
    protected boolean preHandle(ServletRequest request,ServletResponse response) throws Exception {
        log.info("执行JwtFilter的preHandle方法-------->");
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }
//        执行父类的preHandle方法
        return super.preHandle(request, response);

    }

//    PostHandle
    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
        log.info("执行JwtFilter的postHandle方法------->");


    }

    @Override
    public void afterCompletion(ServletRequest request, ServletResponse response, Exception exception) throws Exception {
        log.info("执行JwtFilter的afterCompletion方法------->");
    }


    @Override
    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        log.info("执行JwtFilter的doFilterInternal方法");
        super.doFilterInternal(request, response, chain);
    }
}
